package com.hundsun.cprs.yyt.web.action.trade;

import com.hundsun.cprs.yyt.common.enums.EnumBusinessCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.service.quota.service.QuotaService;
import com.hundsun.cprs.yyt.service.trade.domain.ReturnGoodsFlow;
import com.hundsun.cprs.yyt.service.trade.domain.TradeEntrust;
import com.hundsun.cprs.yyt.service.trade.domain.query.ReturnGoodsFlowQuery;
import com.hundsun.cprs.yyt.service.trade.enums.EnumReturnGoodsFlowStatus;
import com.hundsun.cprs.yyt.service.trade.service.ReturnGoodsFlowService;
import com.hundsun.cprs.yyt.service.trade.service.TradeEntrustService;
import com.hundsun.cprs.yyt.web.action.BaseAction;
import org.apache.commons.lang.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author herong22384
 * @date 2019/7/25 10:38
 */
@Controller
@RequestMapping("trade/entrust/return/")
public class ReturnGoodsAction extends BaseAction {
    @Autowired
    private ReturnGoodsFlowService flowService;
    @Autowired
    private TradeEntrustService entrustService;
    @Autowired
    private QuotaService quotaService;

    @RequestMapping("list")
    public void queryByPage(@ModelAttribute("query")ReturnGoodsFlowQuery query, ModelMap model){
        flowService.queryByPage(query);
        model.addAttribute("flowStatus",EnumReturnGoodsFlowStatus.toMap());
    }

    @RequestMapping(value = "audit",method = RequestMethod.GET)
    public void auditInit(@RequestParam("id")Long id,ModelMap model){
        ReturnGoodsFlow flow = flowService.getReturnGoodsFlowById(id);
        model.addAttribute("flowStatus",EnumReturnGoodsFlowStatus.toMap());
        model.addAttribute("data",flow);
        model.addAttribute("quotaList", quotaService.queryAll());
    }

    @RequestMapping(value = "audit",method = RequestMethod.POST)
    public String audit(ReturnGoodsFlow flow,ModelMap model){
        try{
            //1.获取审核流水详情
            ReturnGoodsFlow returnGoodsFlow = flowService.getReturnGoodsFlowById(flow.getId());
            //2.判断db查出来的流水是否为待审核状态
            if (!returnGoodsFlow.getStatus().equals(EnumReturnGoodsFlowStatus.WAIT_AUDIT.getCode())){
                throw new ServiceCodeException(EnumBusinessCode.BUSSINESS_1705.getErrorNo(),EnumBusinessCode.BUSSINESS_1705.getErrorInfo());
            }
            //3.获取挂售单
            TradeEntrust entrust = entrustService.getTradeEntrustById(returnGoodsFlow.getEntrustId());
            if (entrust == null){
                throw new ServiceCodeException(EnumBusinessCode.BUSSINESS_1703.getErrorNo(),EnumBusinessCode.BUSSINESS_1703.getErrorInfo());
            }
            returnGoodsFlow.setStatus(flow.getStatus());
            //4.校验是否提交退货金额和退货配额
            if (returnGoodsFlow.getStatus().equals(EnumReturnGoodsFlowStatus.PASS_AUDIT.getCode())){
                Validate.notNull(flow.getFundMoney(),"退货金额不能为空");
                Validate.notNull(flow.getReturnQuoteAmount(),"返还配额不能为空");
                //将金额转化为分
                Double returnMoney = new BigDecimal(flow.getFundMoney()).multiply(new BigDecimal(100D)).doubleValue();
                returnGoodsFlow.setReturnFundAmount(returnMoney.longValue());
                returnGoodsFlow.setReturnQuoteAmount(flow.getReturnQuoteAmount());
            }
            returnGoodsFlow.setMemo(flow.getMemo());
            returnGoodsFlow.setQuotaId(flow.getQuotaId());
            flowService.audit(returnGoodsFlow,entrust);
            return success(model,"审核成功","/trade/entrust/return/list");
        }catch (ServiceCodeException e){
            log.error(e);
            if (e.getErrorCode() == 3003){
                return error(model,"审核失败：供应商可用余额不足");
            }else {
                return error(model,"审核失败：" + e.getMessage());
            }
        }catch (Exception e){
            log.error(e);
            return error(model,"审核失败：" + e.getMessage());
        }
    }

    @RequestMapping("view")
    public void view(@RequestParam("id")Long id,ModelMap model){
        model.addAttribute("data",flowService.getReturnGoodsFlowById(id));
        model.addAttribute("flowStatus",EnumReturnGoodsFlowStatus.toMap());
    }

    @Override
    protected void initBinder(WebDataBinder binder) {
        // 注册默认的日期格式化类型: yyyy-MM-dd
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}
